package com.gzdict.common.ext

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Process
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.drake.net.scope.DialogCoroutineScope
import com.gzdict.common.ui.NetRequestDialog
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException

/**
 * 描述: Android 组件扩展
 * @author: create by shang
 * date:2024/3/6 0006 14
 */


fun Activity.versionCode(): Int {
    var localVersion = 0
    try {
        val packageInfo = this.applicationContext.packageManager.getPackageInfo(this.packageName, 0)
        localVersion = packageInfo.versionCode
    } catch (e: PackageManager.NameNotFoundException) {
        e.printStackTrace()
    }
    return localVersion
}

fun Activity.versionName(): String {
    var localVersion = ""
    try {
        val packageInfo = this.applicationContext.packageManager.getPackageInfo(this.packageName, 0)
        localVersion = packageInfo.versionName
    } catch (e: PackageManager.NameNotFoundException) {
        e.printStackTrace()
    }
    return localVersion
}

@Suppress("unused")
fun FragmentActivity.requestDialog(
    msg: String? = "加载中...",
    dialog: Dialog? = NetRequestDialog(msg = msg!!, context = this),
    cancelable: Boolean = true,
    dispatcher: CoroutineDispatcher = Dispatchers.Main,
    block: suspend CoroutineScope.() -> Unit
) = DialogCoroutineScope(this, dialog, cancelable, dispatcher).launch(block)

fun Fragment.startPage(clazz: Class<out Activity>, action: (Activity.(Intent) -> Unit)? = null) {
    Intent(requireActivity(), clazz).let {
        action?.invoke(requireActivity(), it)
        startActivity(it)
    }
}

fun Context.startPage(clazz: Class<out Activity>, action: (Context.(Intent) -> Unit)? = null) {
    Intent(this, clazz).let {
        action?.invoke(this, it)
        if (this !is Activity) {
            it.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        startActivity(it)
    }
}


/**
 * 获取文件uri访问目录
 * provide 配置 xml/file_paths
 * <paths>
 *     <!--物理路径相当于Context.getFilesDir() + /appPath/-->
 *     <files-path name="appPath" path="appPath" />
 * </paths>
 *
 * 同时Manifest添加
 *    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
 *
 *    <provider
 *        android:name="androidx.core.content.FileProvider"
 *        android:authorities="${applicationId}.provider"
 *        android:exported="false"
 *        android:grantUriPermissions="true">
 *        <meta-data
 *            android:name="android.support.FILE_PROVIDER_PATHS"
 *            android:resource="@xml/file_paths" />
 *    </provider>
 *
 *
 */
@Throws(IOException::class)
fun Activity.getFileDir(): File {
    val filePath = File(filesDir, "appPath")
    if (!filePath.exists()) {
        filePath.mkdirs()
    }
    val apkPath = filePath.absolutePath
    val file = File(apkPath, "cash.apk")
    file.delete()
    file.createNewFile()
    return file
}


@Throws(Exception::class)
fun Context.installApk(apkName: File) {
    if (!apkName.exists()) {
        throw FileNotFoundException()
    }
    val intent = Intent(Intent.ACTION_VIEW)
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) //安装完成后打开新版本
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) // 给目标应用一个临时授权
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //判断版本大于等于7.0
        //如果SDK版本>=24，即：Build.VERSION.SDK_INT >= 24，使用FileProvider兼容安装apk
        val authority: String =
            StringBuilder(this.packageName).append(".provider").toString()
        val apkUri = FileProvider.getUriForFile(this, authority, apkName)
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
    } else {
        intent.setDataAndType(
            Uri.fromFile(apkName),
            "application/vnd.android.package-archive"
        )
    }
    this.startActivity(intent)
    Process.killProcess(Process.myPid()) //安装完之后会提示”完成” “打开”。
}

